<template>
  <van-icon
    color="#777"
    :name="isCollected ? 'star' : 'star-o'"
    @click="onCollect"
    :loading="collectLoading"
  />
</template>

<script>
import { collectArtical, cancelArtical } from '@/api/artical.js';
export default {
  name: 'CollectArtical',
  props: {
    isCollected: {
      type: Boolean,
      required: true,
    },
    userId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  data() {
    return {
      // 控制loading的状态
      collectLoading: false,
    };
  },
  methods: {
    async onCollect() {
      try {
        this.loading = true;
        if (this.isCollected) {
          await collectArtical(this.userId);
          // 如果已经收藏了，就将收藏按钮改为实心
          this.$toast('添加收藏成功！');
        } else {
          await cancelArtical(this.userId);
          this.$toast('已取消收藏！');
        }
      } catch (err) {
        console.log(err);
        this.$toast('操作失败，请重试！');
      }
      // 通知父组件去修改视图
      this.$emit('upDateCollect', !this.isCollected);
      this.loading = false;
    },
  },
};
</script>

<style lang="less" scoped></style>
